package com.example.forwardmessages

import android.content.Intent
import android.os.Bundle
import com.google.android.material.snackbar.Snackbar
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.findNavController
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.navigateUp
import androidx.navigation.ui.setupActionBarWithNavController
import android.view.Menu
import android.view.MenuItem
import com.example.forwardmessages.databinding.ActivityMainBinding
import android.util.Log
import android.os.Build
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkManager
import androidx.work.WorkRequest
import java.util.concurrent.TimeUnit

class MainActivity : AppCompatActivity() {

    private lateinit var appBarConfiguration: AppBarConfiguration
    private lateinit var binding: ActivityMainBinding

    private val TAG = "MainActivity"
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        setSupportActionBar(binding.toolbar)

        val navController = findNavController(R.id.nav_host_fragment_content_main)
        appBarConfiguration = AppBarConfiguration(navController.graph)
        setupActionBarWithNavController(navController, appBarConfiguration)

        binding.fab.setOnClickListener { view ->
            // 替换为检查和请求自启动权限的操作
            checkAndRequestAutoStartPermission()
        }
        
        // 在应用启动时检查自启动权限
        checkAndRequestAutoStartPermission()
        
        // 初始化激进保活管理器
        RadicalKeepAliveManager.initialize(this)
        
        // 检查是否有触发邮件发送的intent
        handleIntent(intent)
    }
    
    override fun onDestroy() {
        super.onDestroy()
        // 释放激进保活管理器资源
        if (!isChangingConfigurations) {
            RadicalKeepAliveManager.shutdown(this)
        }
    }
    
    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        // 更新当前intent
        setIntent(intent)
        // 处理新的intent
        handleIntent(intent)
    }
    
    /**
     * 处理intent中的额外参数
     * 使用WorkManager来执行邮件发送，保持向后兼容
     */
    private fun handleIntent(intent: Intent?) {
        if (intent?.getBooleanExtra("TRIGGER_EMAIL_SEND", false) == true) {
            Log.d(TAG, "检测到触发邮件发送的请求，使用WorkManager处理")
            
            // 获取SIM卡信息
            val simInfo = intent.getStringExtra("SIM_INFO") ?: "未知SIM卡"
            Log.d(TAG, "接收到的SIM卡信息: $simInfo")
            
            // 创建WorkRequest
            try {
                val workRequest: WorkRequest = OneTimeWorkRequestBuilder<SmsForwardWorker>()
                    // 添加输入数据
                    .setInputData(
                        androidx.work.Data.Builder()
                            .putString(SmsForwardWorker.KEY_SENDER, "未知发送者")
                            .putString(SmsForwardWorker.KEY_CONTENT, "[通过MainActivity触发的邮件转发]")
                            .putString(SmsForwardWorker.KEY_TIME, java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss", java.util.Locale.getDefault()).format(java.util.Date()))
                            .putString(SmsForwardWorker.KEY_SIM_INFO, simInfo)
                            .build()
                    )
                    // 设置重试策略
                    .setBackoffCriteria(
                        androidx.work.BackoffPolicy.EXPONENTIAL,
                        WorkRequest.MIN_BACKOFF_MILLIS,
                        TimeUnit.MILLISECONDS
                    )
                    .build()

                // 提交任务到WorkManager
                WorkManager.getInstance(this).enqueue(workRequest)
                Log.d(TAG, "通过MainActivity触发的邮件转发任务已调度")
            } catch (e: Exception) {
                Log.e(TAG, "调度邮件转发任务失败", e)
            }
        }
    }
    
    /**
     * 检查并请求自启动权限和相关设置
     */
    private fun checkAndRequestAutoStartPermission() {
        // 检查是否为MIUI系统
        if (MIUIPermissionHelper.isMIUI()) {
            val miuiVersion = MIUIPermissionHelper.getMIUIVersion()
            Log.d(TAG, "检测到MIUI系统，版本: $miuiVersion")
            
            // 使用新的请求方法，这将处理电池优化和自启动权限
            MIUIPermissionHelper.requestAllRequiredPermissions(this)
        } else {
            Log.d(TAG, "非MIUI系统")
            Snackbar.make(binding.fab, "当前系统非MIUI，无需特殊设置", Snackbar.LENGTH_LONG)
                .setAction("确定", null)
                .setAnchorView(R.id.fab).show()
        }
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        // Inflate the menu; this adds items to the action bar if it is present.
        menuInflater.inflate(R.menu.menu_main, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        return when (item.itemId) {
            R.id.action_settings -> true
            else -> super.onOptionsItemSelected(item)
        }
    }

    override fun onSupportNavigateUp(): Boolean {
        val navController = findNavController(R.id.nav_host_fragment_content_main)
        return navController.navigateUp(appBarConfiguration)
                || super.onSupportNavigateUp()
    }
}